﻿using MetroDataQuery.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MetroDataQuery.Utility
{
    public class AllPointChangesQuery
    {
        public static List<List<MonitorPoints>> GetAllValuesByTime(int prjId, List<string> nameArray, string order = "asc")
        {
            using (var db = new MetroProjectsEntities())
            {
                var dictList = (from g in
                                    (from p in db.MonitorPointsDictionary.Where(p => p.PrjId == prjId && nameArray.Contains(p.Name))
                                     group p by new { p.MonitorType, p.Location } into g
                                     select g).ToList()
                                select new tempDict()
                                {
                                    timeList = MonitorPointsQuery.GetMonitorDateTimeList(prjId, g.Key.MonitorType, g.Key.Location).ToList(),
                                    tableName = MetroDataBaseUtility.GetTableNameByMonitorType(prjId, g.Key.MonitorType),
                                    monitorType = g.Key.MonitorType,
                                    nameList = g.Select(t => t.Name).ToList()
                                }).ToList();

                var allTimeList = dictList.Select(p => p.timeList).Aggregate((a, b) => { a.AddRange(b); return a; }).Distinct()
                    .OrderBy(p => p).ToList();
                if (order == "desc")
                {
                    allTimeList.Reverse();
                }

                var results = (from t in allTimeList
                               select ((from p in dictList
                                        select MonitorPointsQuery.GetPointsValueByDateTime(prjId, p.nameList,
                                        p.tableName, t.Value.ToString("yyyy-MM-dd HH:mm:ss")))
                                        .Aggregate((a, b) => { a.AddRange(b); return a; })
                                        .OrderBy(p => nameArray.IndexOf(p.Name)).ToList())
                                        ).ToList();
                return results;
            }
        }

        public class tempDict
        {
            public string monitorType { get; set; }
            public List<string> nameList { get; set; }
            public string tableName { get; set; }
            public List<DateTime?> timeList { get; set; }
        }
    }
}
